//
//  RBWebViewController.m
//  Tourist
//
//  Created by Lan on 2017/7/27.
//  Copyright © 2017年 SummerTea. All rights reserved.
//

#import "RBWebViewController.h"
#import "Masonry.h"
#import "UINavigationController+FDFullscreenPopGesture.h"

static NSString *const GO_BACK_KEY = @"canGoBack";
static NSString *const PROGRESS_KEY = @"estimatedProgress";

#pragma mark - >>>>>ProgressView<<<<

@interface RBWebViewProgressView : UIView

@property(nonatomic, strong) CAGradientLayer *gradientLayer;
@property(nonatomic, strong) CAShapeLayer *progressLayer;
- (void)setProgress: (CGFloat)progress;

@end

@implementation RBWebViewProgressView

- (CAGradientLayer *)gradientLayer
{
    if (!_gradientLayer)
    {
        self.gradientLayer = ({
            CAGradientLayer *gradientLayer = [CAGradientLayer layer];
            UIColor *startColor = [UIColor colorWithRed:83/255.0 green:235/255.0 blue:221/255.0 alpha:1];
            UIColor *endColor = [UIColor greenColor];
            gradientLayer.colors = @[(__bridge id)startColor.CGColor, (__bridge id)endColor.CGColor];
            gradientLayer.locations = @[@0.0, @1.0];
            gradientLayer.startPoint = CGPointMake(0.0, 0.5);
            gradientLayer.endPoint = CGPointMake(1, 0.5);
            [self.layer addSublayer:gradientLayer];
            gradientLayer;
        });
    }
    return _gradientLayer;
}

- (CAShapeLayer *)progressLayer
{
    if (!_progressLayer)
    {
        self.progressLayer = ({
            CAShapeLayer *shapeLayer = [CAShapeLayer layer];
            shapeLayer.strokeEnd = 0.0f;
            shapeLayer.strokeStart = 0.0f;
            shapeLayer.lineCap = kCALineCapRound;
            shapeLayer.fillColor = [UIColor clearColor].CGColor;
            shapeLayer.strokeColor = [UIColor greenColor].CGColor;
            [self.gradientLayer addSublayer:shapeLayer];
            [self.gradientLayer setMask:shapeLayer];
            shapeLayer;
        });
    }
    return _progressLayer;
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    self.gradientLayer.frame = self.bounds;
    self.progressLayer.frame = self.bounds;
    self.progressLayer.lineWidth = CGRectGetHeight(self.frame);
    UIBezierPath *path = [UIBezierPath bezierPath];
    [path moveToPoint:CGPointMake(0, CGRectGetHeight(self.frame)/2)];
    [path addLineToPoint:CGPointMake(CGRectGetWidth(self.frame), CGRectGetHeight(self.frame)/2)];
    self.progressLayer.path = path.CGPath;
}

- (void)setProgress:(CGFloat)progress
{
    //可能有问题,留着
    self.progressLayer.strokeEnd = progress;
    if (progress >= 1)
    {
        [UIView animateWithDuration:0.4 delay:0.5 options:0 animations:^{
            self.alpha = 0;
        } completion:^(BOOL finished) {
            self.progressLayer.strokeEnd = 0;
        }];
    }
    else
    {
        self.alpha = 1;
    }
}

@end

#pragma mark - >>>>>ViewController<<<<<

@interface RBWebViewController ()<WKNavigationDelegate>

@property(nonatomic, strong) WKWebView *webview;
@property(nonatomic, strong) RBWebViewProgressView *progressView;

@property(nonatomic, assign) BOOL firstShow;

@end

@implementation RBWebViewController

#pragma mark - Lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setup];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    if (self.firstShow)
    {
        self.webview.hidden =NO;
        self.progressView.hidden = NO;
        if (self.readyBlock)
        {
            self.readyBlock(self.webview);
        }
    }
}

- (void)dealloc
{
    [_webview removeObserver:self forKeyPath:GO_BACK_KEY];
    [_webview removeObserver:self forKeyPath:PROGRESS_KEY];
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if ([keyPath isEqualToString:GO_BACK_KEY])
    {
        BOOL canGoBack = self.webview.canGoBack;
        self.fd_interactivePopDisabled = canGoBack;
        self.navigationItem.leftBarButtonItems = canGoBack? ({
            NSMutableArray *arrayM = [NSMutableArray array];
            [arrayM addObject:[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"backArror"] style:UIBarButtonItemStylePlain target:self action:@selector(goBack)]];
            [arrayM addObject:[[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"guanbi"] style:UIBarButtonItemStylePlain target:self action:@selector(pop)]];
            arrayM;
        }): nil;
    }
    else if([keyPath isEqualToString:PROGRESS_KEY])
    {
        [self.progressView setProgress:MAX(self.webview.estimatedProgress, 0.3)];
    }
}

#pragma mark - Private

- (void)setup
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.title = self.naviTitle;
    self.firstShow = YES;
}

#pragma mark - Event

- (void)pop
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)goBack
{
    [self.webview goBack];
}

#pragma mark - WKNavigationDelegate

-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{
    //如果是跳转一个新页面
    if (navigationAction.targetFrame == nil) {
        [webView loadRequest:navigationAction.request];
    }
    decisionHandler(WKNavigationActionPolicyAllow);
}

#pragma mark - Getter

- (WKWebView *)webview
{
    if (!_webview)
    {
        self.webview = ({
            WKWebViewConfiguration *configuration = [WKWebViewConfiguration new];
            WKWebView *view = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
            
            view.navigationDelegate = self;
            view.backgroundColor = [UIColor whiteColor];
            view.allowsBackForwardNavigationGestures = YES;
            if (self.urlPath)
            {
                [view loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlPath]]];
            }
            else if(self.html)
            {
                NSString *newHtmlString = [NSString stringWithFormat:@"<meta name='viewport' content='width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0'><meta name='apple-mobile-web-app-capable' content='yes'><meta name='apple-mobile-web-app-status-bar-style' content='black'><meta name='format-detection' content='telephone=no'><script>function show(s){document.location = '%@'+s;}</script><style type='text/css'>img{width:100%%}</style>%@", @"rb_pic_jump", self.html];
                [view loadHTMLString:newHtmlString baseURL:nil];
            }
            [self.view addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.edges.mas_equalTo(0);
            }];
            [view addObserver:self forKeyPath:GO_BACK_KEY options:NSKeyValueObservingOptionNew context:NULL];
            [view addObserver:self forKeyPath:PROGRESS_KEY options:NSKeyValueObservingOptionNew context:NULL];
            
            view;
        });
    }
    return _webview;
}

- (RBWebViewProgressView *)progressView
{
    if (!_progressView)
    {
        self.progressView = ({
            RBWebViewProgressView *view = [RBWebViewProgressView new];
            [self.view addSubview:view];
            [view mas_makeConstraints:^(MASConstraintMaker *make) {
                make.left.top.right.mas_equalTo(0);
                make.height.mas_equalTo(4);
            }];
            [view setProgress:0.3];
            view;
        });
    }
    return _progressView;
}

@end

